package com.kaibes.module.log;

import java.time.LocalDateTime;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import com.kaibes.core.base.util.StringUtils;
import com.kaibes.web.filter.FilterInternal;
import com.kaibes.web.request.RequestBodyListener;

@Component
public class ApiResquestLog implements RequestBodyListener {

    @Override
    public boolean supports(HttpServletRequest request) {
        return request.getContentType() != null;
    }

    @Override
    public byte[] doWithBody(FilterInternal filterInternal, byte[] body) {
        HttpServletRequest request = filterInternal.getRequest();
        request.setAttribute(ApiLogFilter.REQUEST_TIME, LocalDateTime.now());
        Enumeration<String> names = request.getHeaderNames();
        HashMap<String, String> headerMap = new HashMap<>();
        while (names.hasMoreElements()) {
            String key = (String) names.nextElement();
            String value = request.getHeader(key);
            headerMap.put(key, value);
        }
        request.setAttribute(ApiLogFilter.REQUEST, StringUtils.getString(body));
        request.setAttribute(ApiLogFilter.REQUEST_URL, request.getRequestURL().toString());
        request.setAttribute(ApiLogFilter.REQUEST_HEADER, headerMap);
        return body;
    }

}
